package org.jtrace;

import java.util.LinkedList;
import java.util.List;

import org.jtrace.geometry.GeometricObject;
import org.jtrace.geometry.Triangle;
import org.jtrace.primitives.Point3D;
import org.jtrace.primitives.Vector3D;

public class BoundingBox extends GeometricObject {

	private List<Triangle> wrappedTriangles;
	private List<Triangle> facesTriangles;
	
	public BoundingBox(List<Triangle> wrappedTriangles, Point3D max, Point3D min) {
		super(null);
		
		this.wrappedTriangles = wrappedTriangles;
		this.facesTriangles = new LinkedList<Triangle>();
		
		Point3D v11 = new Point3D(min.getX(), min.getY(), min.getZ());
		Point3D v12 = new Point3D(min.getX(), max.getY(), min.getZ());
		Point3D v13 = new Point3D(min.getX(), max.getY(), max.getZ());
		Point3D v14 = new Point3D(min.getX(), min.getY(), max.getZ());
		Point3D v21 = new Point3D(max.getX(), min.getY(), min.getZ());
		Point3D v22 = new Point3D(max.getX(), max.getY(), min.getZ());
		Point3D v23 = new Point3D(max.getX(), max.getY(), max.getZ());
		Point3D v24 = new Point3D(max.getX(), min.getY(), max.getZ());
		
		Vector3D nf = new Vector3D(-1,  0,  0);
		Vector3D nt = new Vector3D( 1,  0,  0);
		Vector3D ns = new Vector3D( 0,  0,  1);
		Vector3D ni = new Vector3D( 0,  0, -1);
		Vector3D ne = new Vector3D( 0,  1,  0);
		Vector3D nd = new Vector3D( 0, -1,  0);
		
		//face frontal
		Triangle f1 = new Triangle(v14, v11, v12, nf, null);
		Triangle f2 = new Triangle(v14, v13, v12, nf, null);
		facesTriangles.add(f1);
		facesTriangles.add(f2);
		
		//face traseira
		Triangle t1 = new Triangle(v24, v21, v22, nt, null);
		Triangle t2 = new Triangle(v24, v23, v22, nt, null);
		facesTriangles.add(t1);
		facesTriangles.add(t2);
		
		//face superior
		Triangle s1 = new Triangle(v24, v14, v13, ns, null);
		Triangle s2 = new Triangle(v24, v23, v13, ns, null);
		facesTriangles.add(s1);
		facesTriangles.add(s2);
		
		//face inferior
		Triangle i1 = new Triangle(v21, v11, v12, ni, null);
		Triangle i2 = new Triangle(v21, v22, v12, ni, null);
		facesTriangles.add(i1);
		facesTriangles.add(i2);
		
		//face esquerda
		Triangle e1 = new Triangle(v24, v21, v11, ne, null);
		Triangle e2 = new Triangle(v24, v14, v11, ne, null);
		facesTriangles.add(e1);
		facesTriangles.add(e2);
		
		//face direita
		Triangle d1 = new Triangle(v12, v22, v23, nd, null);
		Triangle d2 = new Triangle(v12, v13, v23, nd, null);
		facesTriangles.add(d1);
		facesTriangles.add(d2);
		
	}

	@Override
	public Hit hit(Jay jay) {
		
		for (Triangle t : facesTriangles) {
			Hit hit = t.hit(jay);
			if (hit.isHit()) {
				return hit;
			}
		}
		
		return new NotHit();
	}
	
	public List<Triangle> getWrappedTriangles() {
		return wrappedTriangles;
	}
	
}
